//
//  ViewController.m
//  wxDemo
//
//  Created by liuyonghu on 2018/11/1.
//  Copyright © 2018年 liuyonghu. All rights reserved.
//

#define AppId  @"wx64f98d35eee3c8ac"

#define AppSecret @"3344a47541231e18ef22fb4e880178b8"

#import "ViewController.h"
#import <WechatAuthSDK.h>
#import <AFNetworking.h>
#import <CommonCrypto/CommonDigest.h>

@interface ViewController ()<WechatAuthAPIDelegate>
@property(nonatomic,strong) WechatAuthSDK *auth;
@property (weak, nonatomic) IBOutlet UIImageView *qrcodeImageView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    [self getToken];
    _auth = [[WechatAuthSDK alloc]init];
    _auth.delegate =self;
    
//    [auth Auth:@"wx64f98d35eee3c8ac" nonceStr:timeStamp timeStamp:timeStamp scope:@"snsapi_base" signature:@"" schemeData:@""];
    // Do any additional setup after loading the view, typically from a nib.
}



- (void)getToken{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
    
    __block ViewController *selfVC = self;
    [manager GET:@"https://api.weixin.qq.com/cgi-bin/token" parameters:@{
                                                                         @"grant_type":@"client_credential",
                                                                         @"appid":AppId,
                                                                         @"secret":AppSecret
                                                                         } progress:^(NSProgress * _Nonnull downloadProgress) {
                                                                             
                                                                         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                                             NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                                                             //            NSLog(@"responseObject = %@",dic);
                                                                             
                                                                             NSString *access_token = dic[@"access_token"];
                                                                             
                                                                             NSLog(@"access_token = %@",access_token);
//                                                                             获取tiket
                                                                             [selfVC getTiketWithToken:access_token];
                                                                         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                                             
                                                                         }];
}

- (void)getTiketWithToken:(NSString *)token{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=2
    
    __block ViewController *selfVC = self;
    [manager GET:@"https://api.weixin.qq.com/cgi-bin/ticket/getticket" parameters:@{
                                                                         @"access_token":token,
                                                                         @"type":@"2"
                                                                         } progress:^(NSProgress * _Nonnull downloadProgress) {
                                                                             
                                                                         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                                             NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//                                                                                         NSLog(@"responseObject = %@",dic);
                                                                             
                                                                             NSString *access_token = dic[@"ticket"];
//                                                                             获取signStr
                                                                             [selfVC getSignStrwithTiket:access_token];
                                                                         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                                             
                                                                         }];
}


-(NSString *)getSignStrwithTiket:(NSString *)tiket{
    NSString *timestamp = [NSString stringWithFormat:@"%0.f", [[NSDate date] timeIntervalSince1970] *1000];
//    NSLog(@"timestamp = %@",timestamp);
      NSString *timestampStr = [NSString stringWithFormat:@"timestamp%@",timestamp];
    NSArray *keys = @[@"appid",@"noncestr",@"sdk_ticket",@"timestamp"];
    NSDictionary *par = @{@"appid":@"wx64f98d35eee3c8ac",@"noncestr":timestampStr,@"sdk_ticket":tiket,@"timestamp":timestamp};
    NSArray *sortedArr = [keys sortedArrayUsingSelector:@selector(compare:)];
    
    NSMutableString *sortedStr = [[NSMutableString alloc]init];
    
    for (NSInteger i = 0; i < sortedArr.count; i ++) {
        NSString *key = sortedArr[i];
        NSString *value = [par valueForKey:key];
        NSString *tempStr;
        if (i) {
            tempStr = [NSString stringWithFormat:@"&%@=%@",key,value];
        }else{
           tempStr = [NSString stringWithFormat:@"%@=%@",key,value];
        }
        
       sortedStr =  [[sortedStr stringByAppendingString:tempStr] copy];
        
        
    }
    
    NSLog(@"sortedStr = %@",sortedStr);
    
    NSString *signStr = [self sha1:sortedStr];
       NSLog(@"signStr = %@",signStr);
    Boolean auth =  [_auth Auth:@"wx64f98d35eee3c8ac" nonceStr:timestampStr timeStamp:timestamp scope:@"snsapi_userinfo,snsapi_base" signature:signStr schemeData:@""];
    NSLog(@"auth = %d",auth);
    
    return sortedStr;
}


- (NSString*) sha1:(NSString*)input
 {
     const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
       NSData *data = [NSData dataWithBytes:cstr length:input.length];
   
        uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
       CC_SHA1(data.bytes, data.length, digest);
    
        NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
        for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
                 [output appendFormat:@"%02x", digest[i]];
    
        return output;

 }


  //得到二维码
- (void)onAuthGotQrcode:(UIImage *)image{
    NSLog(@"image  = %@",image);
    self.qrcodeImageView.image = image;
}
//二维码被扫描
- (void)onQrcodeScanned{
    NSLog(@"onQrcodeScanned");
}
 //成功登录
- (void)onAuthFinish:(int)errCode AuthCode:(NSString *)authCode{
    NSLog(@"onAuthFinish authCode = %@  errCode= %d",authCode,errCode);
    [self getUioniDWithauthCode:authCode];
}

- (void)getUioniDWithauthCode:(NSString *)code{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=2
    
    __block ViewController *selfVC = self;
    [manager GET:@"https://api.weixin.qq.com/sns/oauth2/access_token" parameters:@{
                                                                                    @"appid":AppId,
                                                                                    @"secret":AppSecret,
                                                                                    @"code":code,
                                                                                    @"grant_type":@"authorization_code"
                                                                                    } progress:^(NSProgress * _Nonnull downloadProgress) {
                                                                                        
                                                                                    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                                                        NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                                                                        NSLog(@"getUioniDWithauthCode = %@",dic);
                                                                                        
//                                                                                        NSString *access_token = dic[@"ticket"];
                                                                                        //
                                                                                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                                                        
                                                                                    }];
}
@end
